/**
 * PictureServiceImpl.java
 * @author
 * 作者 屈甲康 
 */
package org.jackysoft.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jackysoft.entity.Picture;
import org.jackysoft.service.AbstractIdentifiedService;
import org.jackysoft.service.AbstractStringIdServiceImpl;
import org.jackysoft.service.PictureService;
import org.jackysoft.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.google.common.collect.Lists;

@Service
@Transactional
public class PictureServiceImpl extends AbstractStringIdServiceImpl<Picture>
		implements PictureService {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8033050227131970220L;
	final static Log logger = LogFactory.getLog(PictureServiceImpl.class);

	public PictureServiceImpl() {
		this.type = Picture.class;
	}

	@Override
	public void create(File file, String name) throws Exception {
		
	    super.create(picture(file,name));
	}

	@Override
	public void create(File[] files, String[] names) throws Exception {
		Collection<Picture> pics = Lists.newArrayList();
	    for(int i=0;i<files.length;i++){
	         pics.add(picture(files[i],names[i]));
	    }
	    super.create(pics);
	}
	
	Picture picture(File file ,String name) throws Exception{
		
		Assert.notNull(file);
		String base = this.getConfig().getImageDir();
		char lc = base.charAt(base.length() - 1);
		boolean hasEnd = false;
		hasEnd = (lc == '/' || lc == '\\');
		if (!hasEnd)
			base += File.separator;
		String realName = UUID.randomUUID().toString()+"."+StringUtils.splitPostFileName(file.getName());
		Picture pic = new Picture();
		pic.setName(name);
		pic.setRealName(realName);
		pic.setSize(file.length());
		pic.setStorePath(base+realName);
	    IOUtils.copy(new FileInputStream(file), new FileOutputStream(new File(pic.getStorePath())));		
		return pic;
		
	}
	
	

}